
package com.be.beadmin.quality.impl;

import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.product.entity.ErrorReport;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.quality.dto.input.InspectionFileInfoByInspectionTypeAndIdPage;
import com.be.beadmin.quality.entity.InspectionFileInfo;
import com.be.beadmin.quality.entity.InspectionFileInfo_;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.service.impl.MinioService;
import com.be.beadmin.service.service.SerialNumberService;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.quality.mapper.InspectionFileInfoMapperEx;
import com.be.beadmin.quality.repository.InspectionFileInfoRepository;
import com.be.beadmin.quality.service.InspectionFileInfoService;
import com.be.beadmin.quality.dto.input.InspectionFileInfoDto;
import com.be.beadmin.quality.dto.output.InspectionFileInfoEx;
import com.be.beadmin.quality.mapper.InspectionFileInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description 服务实现
* @author ljh
* @date 2023-07-13
**/
@Service
@RequiredArgsConstructor
public class InspectionFileInfoServiceImpl implements InspectionFileInfoService {

    @Autowired
    private  InspectionFileInfoRepository inspectionFileInfoRepository;
    @Autowired
    private  InspectionFileInfoMapper inspectionFileInfoMapper;
    @Autowired
    private  InspectionFileInfoMapperEx inspectionFileInfoExMapper;

    @Autowired
    private SerialNumberService serialNumberService;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    @Override
    public Page<InspectionFileInfoEx> getInspectionFileInfoByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<InspectionFileInfo> page = inspectionFileInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectionFileInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectionFileInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<InspectionFileInfoEx> page1 = page.map(inspectionFileInfoExMapper::toEntity);
            return page1;
    }

    @Override
    public Page<InspectionFileInfoEx> getInspectionFileInfoByPageAndInspectionTypeAndId(InspectionFileInfoByInspectionTypeAndIdPage inspectionFileInfoByInspectionTypeAndIdPage) {
        PageEntity pageEntity = inspectionFileInfoByInspectionTypeAndIdPage.getPageEntity();
        String inspectionType = inspectionFileInfoByInspectionTypeAndIdPage.getInspectionType();
        String id = inspectionFileInfoByInspectionTypeAndIdPage.getId();
        if(inspectionType==null) throw new BeadminException("未指定检验类型");
        if(id==null) throw new BeadminException("未指定标识id（用于入厂检的入厂检验id/过程检验的生产工序id/...）");
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<InspectionFileInfo> page = inspectionFileInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectionFileInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(InspectionFileInfo_.inspectionType), inspectionType);
                    list.add(pre3);
                    if(inspectionType.equals("柜体入厂检验")){
                        Predicate pre4 = criteriaBuilder.equal(root.get(InspectionFileInfo_.PRODUCT_QUALITY_ID), id);
                        list.add(pre4);
                    }else if(inspectionType.equals("过程检验")){
                        Predicate pre4 = criteriaBuilder.equal(root.get(InspectionFileInfo_.PRODUCT_MANUFACT_INFOR_ID), id);
                        list.add(pre4);
                    }
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectionFileInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<InspectionFileInfoEx> page1 = page.map(inspectionFileInfoExMapper::toEntity);
        return page1;
    }

    @Override
    public String getInspectPreviewUrl(InspectionFileInfoDto inspectionFileInfoDto) throws Exception {
        String fileCode = inspectionFileInfoDto.getInspectionFileCode();
        String fileName = inspectionFileInfoDto.getInspectionFileName();
        String FileName = fileCode+"+"+fileName ;
        String preview_url = minioUtil.getPreviewFileUrl(inspectionFileInfoDto.getBucketName(),FileName);
        inspectionFileInfoDto.setFileUrl(preview_url);
        InspectionFileInfo inspectionFileInfo = inspectionFileInfoMapper.toEntity(inspectionFileInfoDto);
        inspectionFileInfoRepository.save(inspectionFileInfo);
        return preview_url;
    }

    @Override
    public void addInspectionFileInfo(InspectionFileInfoDto inspectionFileInfoDto) {
            InspectionFileInfo result = inspectionFileInfoRepository.findInspectionFileInfoByIdAndDelete(inspectionFileInfoDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("InspectionFileInfo不存在,请重新查询");
            }
            InspectionFileInfo inspectionFileInfo = inspectionFileInfoMapper.toEntity(inspectionFileInfoDto);
            inspectionFileInfoRepository.save(inspectionFileInfo);
    }

    @Override
    public void updateInspectionFileInfo(InspectionFileInfoDto inspectionFileInfoDto) {
            InspectionFileInfo inspectionFileInfo = inspectionFileInfoRepository.findInspectionFileInfoById(inspectionFileInfoDto.getId());
            inspectionFileInfo = inspectionFileInfoMapper.toEntity(inspectionFileInfoDto);
            inspectionFileInfoRepository.save(inspectionFileInfo);
    }


    @Override
    public void delInspectionFileInfo(String id) {
        InspectionFileInfo inspectionFileInfo = inspectionFileInfoRepository.findInspectionFileInfoById(id);
        inspectionFileInfo.setDelete(1);
        inspectionFileInfoRepository.save(inspectionFileInfo);
    }

    @Override
    public void delInspectionFileInfos (List<String> ids) { }

    @Override
    public void uploadInspectionFileInfo(String inspectionType, String id, String uploaderId, String uploaderName, Date uploadTime, MultipartFile[] multipartFile, String bucketName) throws Exception {
        InspectionFileInfo inspectionFileInfo = new InspectionFileInfo();
        inspectionFileInfo.setInspectionType(inspectionType);
        if(inspectionType.equals("柜体入厂检验")){
            inspectionFileInfo.setProductQualityId(id);
        }else if (inspectionType.equals("过程检验") || inspectionType.equals("终检") || inspectionType.equals("交检评审")){
            inspectionFileInfo.setProductManufactInforId(id);
            inspectionFileInfo.setInspectionTaskId(id);
        }
        //其他检验类型。。。。。

        inspectionFileInfo.setUploaderId(uploaderId);
        inspectionFileInfo.setUploaderName(uploaderName);
        inspectionFileInfo.setUploadTime(uploadTime);

        //附件相关
        for(MultipartFile file:multipartFile) {
            if (file != null) {
                inspectionFileInfo.setInspectionFileCode(serialNumberService.getNextSnByCode("FileCode"));
                inspectionFileInfo.setInspectionFileName(file.getOriginalFilename());
                inspectionFileInfo.setBucketName(bucketName);

                String uploadFileName = inspectionFileInfo.getInspectionFileCode() + "+" + inspectionFileInfo.getInspectionFileName();

                String preview_url = minioUtil.uploadFile2(file, uploadFileName, bucketName);
                inspectionFileInfo.setFileUrl(preview_url);
            }

            inspectionFileInfoRepository.save(inspectionFileInfo);
        }
    }

}